/*
 * @Author: MarioGo
 * @Date: 2021-11-04 22:30:26
 * @LastEditTime: 2021-11-20 16:30:05
 * @LastEditors: MarioGo
 * @Description: 文件描述
 * @FilePath: /zheye/src/store.ts
 * 可以输入预定的版权声明、个性签名、空行等
 */
/* eslint-disable prefer-const */
import { createStore, Commit } from 'vuex';
import { testPosts } from './testData';
import axios, { AxiosRequestConfig } from 'axios';
import { signAPI, columnAPI } from './api/index';
import { StorageHandler, storageType } from './utils/storage';
const storageHandler = new StorageHandler();
export interface GlobalErrorProps {
  status: boolean;
  message?: string;
}

export interface ResultPromiseProps {
  code?: number;
  msg?: string;
  results?: [];
  success?: boolean;
  data?: string;
  errcode?: number;
  errmsg?: string;
}
export interface ImageProps {
  _id?: string;
  url?: string;
  createdAt?: string;
  fitUrl?: string;
}
export interface PostProps {
  id?: string;
  title: string;
  excerpt?: string;
  content?: string;
  image?: ImageProps | string;
  createdAt?: string;
  column: string;
  author?: string | UserProps;
  isHTML?: boolean;
}
export interface UserProps {
  isLogin: boolean;
  name?: string;
  id?: number;
  columnId?: number;
}
interface ListProps<P> {
  [id: string]: P;
}
export interface LoadedPostProps {
  columnId?: string;
  currentPage?: number;
  total?: number;
}

export interface GlobalDataProps {
  token: string;
  error: GlobalErrorProps;
  loading: boolean;
  columns: {
    data: ListProps<ColumnProps>;
    currentPage: number;
    total: number;
  };
  posts: {
    data: ListProps<PostProps>;
    loadedColumns: ListProps<LoadedPostProps>;
  };
  user: UserProps;
}
export interface ColumnProps {
  id: number;
  title: string;
  avatar?: string;
  description: string;
}

const testData: ColumnProps[] = [];

const store = createStore({
  state: {
    token: storageHandler.getItem(storageType, 'token') || '',
    error: { status: false },
    loading: false,
    columns: testData,
    posts: testPosts,
    user: { id: 1, name: '李哲坤', isLogin: false, columnId: 1 },
  },
  mutations: {
    setLoading(state, status) {
      state.loading = status;
    },
    setError(state, e: GlobalErrorProps) {
      state.error = e;
    },
    LOGIN(state, rawData) {
      const { token } = rawData.data;
      state.token = token;
      storageHandler.setItem(storageType, 'token', token);
      axios.defaults.headers.common.Authorization = `Bearer ${token}`;
      state.user = { ...state.user, isLogin: rawData.success };
    },
    LOGOUT(state) {
      state.user = { ...state.user, isLogin: false };
    },
    SETCOLUMN(state, data) {
      state.columns = data;
    },
    createPost(state, newPost) {
      state.posts.push(newPost);
    },
  },
  actions: {
    // 登录示例
    loginActionFetch({ commit }, loginData) {
      return signAPI
        .signIn(loginData)
        .then((res) => {
          commit('LOGIN', res);
          return res;
        })
        .catch((error) => {
          console.log('e :>> ', error);
          return error;
        });
    },
    //注销多请求示例
    async singoutActionFetch({ commit }) {
      try {
        let [a, b] = await Promise.all([signAPI.signOut(), signAPI.signOut2()] as
          | ResultPromiseProps[]
          | [null, null]);
        commit('LOGOUT');
        console.log('%c 🥃 a, b: ', 'font-size:20px;background-color: #4b4b4b;color:#fff;', a, b);
        if (a?.success && b?.success) {
          return { a, b };
        }
        // const result = res.some((r: any) => r.success || '');
        // console.log('注销res :>> ', result, res);
      } catch (error) {
        console.log('注销error :>> ', error);
        return error;
      }
    },
    columnActionFetch({ commit }) {
      return columnAPI
        .getList()
        .then((res) => {
          commit('SETCOLUMN', res);
          return res;
        })
        .catch((error) => {
          console.log('error :>> ', error);
        });
    },
  },
  getters: {
    biggerColumnsLen(state) {
      if (state.columns.length > 1) {
        return state.columns.filter((x) => x.id > 2).length;
      }
    },
  },
});

/**
 *
 * @param url  请求路径
 * @param mutationName 获取请求数据之后的 commit操作类型
 * @param config 请求参数
 * @param commit  vuex自带方法
 * @param extraData  refeasapi配置项
 * @returns
 */
const asyncAndCommit = async (
  url: string,
  mutationName: string,
  config: AxiosRequestConfig = { method: 'get' },
  commit: Commit,
  extraData?: unknown,
) => {
  // 请求回来后的返回值
  const { data } = await axios(url, config);
  //根据请求处理 commit中的值
  if (extraData) {
    commit(mutationName, { data, extraData });
  } else {
    commit(mutationName, data);
  }
  return data;
};

export default store;
